'use strict'

const { Controller } = require('egg')
const fs = require('mz/fs')

class utlis extends Controller {
    async upImage() {
        const { ctx } = this
        const imgPath = []
        const error = {}
        const filesName = ctx.request.body.filesName || 'default'

        if (!ctx.request.files) {
            return ctx.returnBody(403, '没有上传文件')
        }
        for (let file of ctx.request.files) {
            let result, suffix
            const {
                filename,
                filepath
            } = file
            try {
                filename.indexOf('.gif') === -1
                    ? suffix = 'png'
                    : suffix = 'gif'
                const name = `${filesName}/${ctx.app.md5(filename)}.${suffix}`
                result = await ctx.service.cos.upload(name, filepath)
                console.log(result)
                debugger
                if (result.statusCode === 200) {
                    imgPath.push(`https://${result.Location}`)
                } else {
                    Object.assign(error, result)
                }
            } finally {
                await fs.unlink(file.filepath)
            }
        }

        if ('error' in error) {
            ctx.returnBody(400, '上传失败', error)
        } else {
            ctx.returnBody(200, '上传成功', {
                success: true,
                file_path: imgPath
            })
        }
    }
}

module.exports = utlis